from time import sleep
# 引入selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
# 弹窗库
import tkinter as tk
from tkinter import messagebox
# 随机生成数据
import random

# 定义全局的变量
indices_to_click1 = []
indices_to_click2 = []
indices_to_click3 = []


def init():
    path = "chromedriver.exe"
    service = Service(executable_path=path)
    browser = webdriver.Chrome(service=service)
    url = 'https://www.wjx.cn/vm/hs1zf89.aspx'
    browser.get(url)
    begin_button = browser.find_element(By.CLASS_NAME, 'slideChunkWord')
    begin_button.click()
    return browser


def topic1(browser, indices_to_click):
    topic1 = browser.find_element(By.ID, "q1_3")
    browser.execute_script("arguments[0].click();", topic1)
    first_outer_div = browser.find_element(By.CLASS_NAME, 'ui-checkbox')
    browser.execute_script("arguments[0].click();", first_outer_div)
    all_outer_divs = browser.find_elements(By.CLASS_NAME, 'ui-checkbox')
    sleep(2)
    for index, div in enumerate(all_outer_divs):
        if index + 1 in indices_to_click:
            sleep(0.8)
            browser.execute_script("arguments[0].click();", div)


def topic2(browser, indices_to_click):
    all_outer_divs = browser.find_elements(By.CLASS_NAME, 'ui-radio')
    for index, div in enumerate(all_outer_divs):
        if index + 1 in indices_to_click:
            sleep(0.8)
            browser.execute_script("arguments[0].click();", div)


def topic3(browser, indices_to_click):
    all_outer_divs = browser.find_elements(By.CLASS_NAME, 'rate-off')
    for index, div in enumerate(all_outer_divs):
        if index + 1 in indices_to_click:
            sleep(0.8)
            browser.execute_script("arguments[0].click();", div)


def submit(browser):
    submit_button = browser.find_element(By.ID, 'ctlNext')
    browser.execute_script("arguments[0].click();", submit_button)


def window():
    root = tk.Tk()
    root.title("wfl的青城山旅游服务质量调查问卷批量生成工具")
    root.geometry("500x500")
    root.resizable(False, False)

    def clear_form():
        for widget in form_frame.winfo_children():
            widget.destroy()

    def on_entry_click(event, entry):
        """ 如果用户点击输入框，清空提示文本 """
        if entry.get() == "请输入选项序号，用逗号分隔":
            entry.delete(0, tk.END)  # 清空提示文本
            entry.config(fg='black')  # 设置输入框文本颜色为黑色

    def on_focusout(event, entry):
        """ 如果输入框为空，则重新设置提示文本 """
        if entry.get() == "":
            entry.insert(0, "请输入选项序号，用逗号分隔")
            entry.config(fg='gray')  # 设置提示文本颜色为灰色

    def generate_custom_data():
        clear_form()
        tk.Label(form_frame, text="请填写以下问题（多选选项用逗号隔开）：").grid(row=0, column=0, columnspan=2, pady=10)
        entries.clear()

        placeholders = {
            1: "1~5范围内多选，逗号隔开",
            2: "1~4范围内单选",
            3: "1~5范围内单选",
            4: "1~5范围内单选12次，逗号隔开",
            5: "1~6范围内多选，逗号隔开",
            6: "1~2范围内单选",
            7: "1~6范围内单选",
            8: "1~5范围内单选",
            9: "1~5范围内单选",
            10: "1~4范围内单选",
            11: "1~6范围内单选"
        }

        for i in range(11):
            question_label = tk.Label(form_frame, text=f"第 {i + 1} 题:")
            question_label.grid(row=(i // 2) + 1, column=(i % 2) * 2, padx=5, pady=5, sticky="e")

            entry = tk.Entry(form_frame)
            placeholder_text = placeholders.get(i + 1)
            entry.insert(0, placeholder_text)  # 添加提示文本
            entry.config(fg='gray')  # 设置提示文本颜色为灰色
            entry.grid(row=(i // 2) + 1, column=(i % 2) * 2 + 1, padx=5, pady=5, sticky="w")

            # 使用 lambda 表达式传递当前的 entry 以避免共享变量问题
            entry.bind("<FocusIn>",
                       lambda event, entry=entry, text=placeholder_text: on_entry_click(event, entry, text))
            entry.bind("<FocusOut>", lambda event, entry=entry, text=placeholder_text: on_focusout(event, entry, text))

            entries.append(entry)

        execute_button = tk.Button(form_frame, text="执行", command=submit_custom_data)
        execute_button.grid(row=7, column=0, columnspan=2, pady=10)

    def on_entry_click(event, entry, placeholder_text):
        if entry.get() == placeholder_text:
            entry.delete(0, "end")
            entry.config(fg='black')

    def on_focusout(event, entry, placeholder_text):
        if entry.get() == "":
            entry.insert(0, placeholder_text)
            entry.config(fg='gray')

    # 提交自定义数据
    def submit_custom_data():
        data = [entry.get().strip() for entry in entries]
        if any(not item for item in data):
            messagebox.showwarning("警告", "请确保所有问题均已填写完毕！")
        else:
            print("用户填写的数据：", data)
            # 替换中文逗号‘，’为英文逗号','
            cleaned_data = [item.replace('，', ',') for item in data]
            i = 1
            for datum in cleaned_data:
                if i == 1 or i == 5:
                    if "," in datum:
                        str_data = datum.split(",")
                    else:
                        str_data = [datum]
                    indices_to_click1.append(str_data)
                    i += 1
                elif i == 2 or i == 3 or i == 6 or i == 7 or i == 8 or i == 9 or i == 10 or i == 11:
                    if "," in datum:
                        str_data = datum.split(",")
                    else:
                        str_data = [datum]
                    indices_to_click2.append(str_data)
                    i += 1
                elif i == 4:
                    if "," in datum:
                        str_data = datum.split(",")
                    else:
                        str_data = [datum]
                    indices_to_click3.append(str_data)

                    i += 1
            times = int(entry_count.get())  # 获取执行次数
            for _ in range(times):
                # 执行函数自动化程序
                # print(execute_times)
                # print(times)
                # print(times)
                actuator()

    # 点击随机生成数据按钮
    def generate_random_data():
        execute_times = int(entry_count.get())  # 获取执行次数
        # Assuming you have your Tkinter Label object created as 'status_label'
        status_label = tk.Label(form_frame, text="正在生成随机数据，请等待执行……")
        status_label.pack(pady=10)
        for _ in range(execute_times):
            clear_form()
            random_button.config(state="disabled", text="请等待 5 秒...")
            tk.Label(form_frame, text="正在生成随机数据，请等待执行……").pack(pady=10)
            result1, result2, result3 = map_choices_random()
            browser = init()
            topic1(browser, result1[0])
            topic1(browser, result1[1])
            topic2(browser, result2)
            topic3(browser, result3)
            sleep(3)
            submit(browser)
            sleep(3)
            browser.quit()
            print("随机生成若干数据按钮被点击，当前执行的次数为：")
            root.after(5000, reset_random_button)
        # After the loop finishes, update the label text to indicate completion
        status_label.config(text="自动化脚本已经执行结束，请继续操作......")

    def reset_random_button():
        random_button.config(state="normal", text="随机生成若干数据")

    warning_label = tk.Label(root, text="请合理设置执行次数，避免影响程序运行", fg="red")
    warning_label.pack(pady=5)

    count_frame = tk.Frame(root)
    count_frame.pack(pady=10)

    tk.Label(count_frame, text="执行次数：").pack(side="left")
    entry_count = tk.Entry(count_frame, width=5)
    entry_count.insert(0, "1")
    entry_count.pack(side="left")
    # 获取执行次数
    try:
        execute_times = int(entry_count.get())  # 获取执行次数
    except ValueError:
        messagebox.showerror("输入错误", "请输入有效的执行次数（数字）")
        return

    button_frame = tk.Frame(root)
    button_frame.pack(pady=10)

    custom_button = tk.Button(button_frame, text="生成自定义若干数据", command=generate_custom_data)
    custom_button.pack(side="left", padx=5)

    random_button = tk.Button(button_frame, text="随机生成若干数据", command=generate_random_data)
    random_button.pack(side="left", padx=5)

    form_frame = tk.Frame(root)
    form_frame.pack(pady=20)

    entries = []
    root.mainloop()


# 运行自动化
def actuator():
    browser = init()

    # 数据处理
    result1, result2, result3 = data_processing(indices_to_click1, indices_to_click2, indices_to_click3[0])
    # print("处理后的数据：", result1, result2, result3)
    # print(result3)
    # print(indices_to_click3)
    topic1(browser, result1[0])
    topic1(browser, result1[1])
    topic2(browser, result2)
    topic3(browser, result3)
    sleep(3)
    submit(browser)
    sleep(3)
    browser.quit()


# 处理表单输入的三个参数
def data_processing(data1, data2, data3):
    # 分别定义三个映射集
    choice_mapping_data1 = {
        1: list(range(1, 6)),  # 第1题：选项范围1~5
        5: list(range(6, 12)),  # 第5题：选项范围6~11
    }

    choice_mapping_data2 = {
        2: list(range(1, 5)),  # 第2题：选项范围1~4
        3: list(range(5, 10)),  # 第3题：选项范围5~9
        6: list(range(10, 12)),  # 第6题：选项范围10~11
        7: list(range(12, 18)),  # 第7题：选项范围12~17
        8: list(range(18, 23)),  # 第8题：选项范围18~22
        9: list(range(23, 28)),  # 第9题：选项范围23~27
        10: list(range(28, 32)),  # 第10题：选项范围28~31
        11: list(range(32, 38))  # 第11题：选项范围32~37
    }

    choice_mapping_data3 = {
        4: [
            list(range(1, 6)), list(range(6, 11)), list(range(11, 16)),
            list(range(16, 21)), list(range(21, 26)), list(range(26, 31)),
            list(range(31, 36)), list(range(36, 41)), list(range(41, 46)),
            list(range(46, 51)), list(range(51, 56)), list(range(56, 61))
        ]
    }

    # 将嵌套字符串列表转为整数
    data1 = [[int(x) for x in group] for group in data1]
    data2 = [[int(x) for x in group] for group in data2]
    data3 = [[int(x) for x in group] for group in data3]

    # 结果数组初始化
    result1, result2, result3 = [], [], []

    # 处理 data1：第1题和第5题
    for idx, values in enumerate(data1):
        if idx == 0:  # 第1题
            result1.append([choice_mapping_data1[1][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[1])])
        elif idx == 1:  # 第5题
            result1.append([choice_mapping_data1[5][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[5])])

    # 处理 data2：第2题到第11题
    for idx, values in enumerate(data2):

        if idx == 0:  # 第2题
            result2.extend(
                [choice_mapping_data2[2][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[2])])
        elif idx == 1:  # 第3题
            result2.extend(
                [choice_mapping_data2[3][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[3])])
        elif idx == 2:  # 第6题
            result2.extend(
                [choice_mapping_data2[6][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[6])])
        elif idx == 3:  # 第7题
            result2.extend(
                [choice_mapping_data2[7][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[7])])
        elif idx == 4:  # 第8题
            result2.extend(
                [choice_mapping_data2[8][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[8])])
        elif idx == 5:  # 第9题
            result2.extend(
                [choice_mapping_data2[9][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[9])])
        elif idx == 6:  # 第10题
            result2.extend(
                [choice_mapping_data2[10][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[10])])
        elif idx == 7:  # 第11题
            result2.extend(
                [choice_mapping_data2[11][i - 1] for i in values if 1 <= i <= len(choice_mapping_data2[11])])

    # 处理 data3：第4题
    question_num = 4  # 第4题
    if question_num in choice_mapping_data3:
        group_results = choice_mapping_data3[question_num]  # 获取第4题的12个范围
        for i, group in enumerate(group_results):
            # 对于每个范围的值，只取第一个值来表示
            if len(data3) > i and data3[i]:  # 确保索引不超出范围
                result3.append(group[data3[i][0] - 1] if 1 <= data3[i][0] <= len(group) else group[0])

    return result1, result2, result3


def generate_and_map_choices():
    # 定义映射集
    choice_mapping_data1 = {
        1: list(range(1, 6)),  # 第1题：选项范围1~5
        5: list(range(6, 12)),  # 第5题：选项范围6~11
    }

    choice_mapping_data2 = {
        2: list(range(1, 5)),  # 第2题：选项范围1~4
        3: list(range(5, 10)),  # 第3题：选项范围5~9
        6: list(range(10, 12)),  # 第6题：选项范围10~11
        7: list(range(12, 18)),  # 第7题：选项范围12~17
        8: list(range(18, 23)),  # 第8题：选项范围18~22
        9: list(range(23, 28)),  # 第9题：选项范围23~27
        10: list(range(28, 32)),  # 第10题：选项范围28~31
        11: list(range(32, 38)),  # 第11题：选项范围32~37
    }

    choice_mapping_data3 = {
        4: [
            list(range(1, 6)), list(range(6, 11)), list(range(11, 16)),
            list(range(16, 21)), list(range(21, 26)), list(range(26, 31)),
            list(range(31, 36)), list(range(36, 41)), list(range(41, 46)),
            list(range(46, 51)), list(range(51, 56)), list(range(56, 61))
        ]
    }

    # 随机生成测试数据
    data1 = [[random.randint(1, 5) for _ in range(2)], [random.randint(1, 6) for _ in range(2)]]  # 第1和第5题
    data2 = [[random.randint(1, 4)] for _ in range(8)]  # 第2题到第11题
    data3 = [[random.randint(1, 5)] for _ in range(12)]  # 第4题的12个范围

    # 结果数组初始化
    result1, result2, result3 = [], [], []

    # 处理 data1：第1题和第5题
    for idx, values in enumerate(data1):
        if idx == 0:  # 第1题
            result1.append([choice_mapping_data1[1][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[1])])
        elif idx == 1:  # 第5题
            result1.append([choice_mapping_data1[5][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[5])])

    # 处理 data2：第2题到第11题
    for idx, values in enumerate(data2):
        question_num = idx + 2  # 第2题到第11题
        if question_num in choice_mapping_data2:
            result2.extend(
                [choice_mapping_data2[question_num][i - 1] for i in values if
                 1 <= i <= len(choice_mapping_data2[question_num])]
            )

    # 处理 data3：第4题
    question_num = 4  # 第4题
    if question_num in choice_mapping_data3:
        group_results = choice_mapping_data3[question_num]  # 获取第4题的12个范围
        for i, group in enumerate(group_results):
            # 对于每个范围的值，只取第一个值来表示
            if len(data3) > i and data3[i]:  # 确保索引不超出范围
                result3.append(group[data3[i][0] - 1] if 1 <= data3[i][0] <= len(group) else group[0])

    return result1, result2, result3


# 随机生成数据
def map_choices_random(data1=None, data2=None, data3=None):
    # 定义映射集
    choice_mapping_data1 = {
        1: list(range(1, 6)),  # 第1题：选项范围1~5
        5: list(range(6, 12)),  # 第5题：选项范围6~11
    }

    choice_mapping_data2 = {
        2: list(range(1, 5)),  # 第2题：选项范围1~4
        3: list(range(5, 10)),  # 第3题：选项范围5~9
        6: list(range(10, 12)),  # 第6题：选项范围10~11
        7: list(range(12, 18)),  # 第7题：选项范围12~17
        8: list(range(18, 23)),  # 第8题：选项范围18~22
        9: list(range(23, 28)),  # 第9题：选项范围23~27
        10: list(range(28, 32)),  # 第10题：选项范围28~31
        11: list(range(32, 38)),  # 第11题：选项范围32~37
    }

    choice_mapping_data3 = {
        4: [
            list(range(1, 6)), list(range(6, 11)), list(range(11, 16)),
            list(range(16, 21)), list(range(21, 26)), list(range(26, 31)),
            list(range(31, 36)), list(range(36, 41)), list(range(41, 46)),
            list(range(46, 51)), list(range(51, 56)), list(range(56, 61))
        ]
    }

    # 自动生成随机数据（如果没有传入 data1, data2, data3）
    if data1 is None or data2 is None or data3 is None:
        data1 = [[str(random.randint(1, 5)) for _ in range(2)], [str(random.randint(1, 6)) for _ in range(2)]]  # 第1和第5题
        data2 = [[str(random.randint(1, 4))] for _ in range(8)]  # 第2题到第11题
        data3 = [[str(random.randint(1, 5))] for _ in range(12)]  # 第4题的12个范围

    # 将字符串数据转换为整数
    data1 = [[int(x) for x in group] for group in data1]
    data3 = [[int(x) for x in group] for group in data3]

    # 结果数组初始化
    result1, result2, result3 = [], [], []

    # 处理 data1：第1题和第5题
    for idx, values in enumerate(data1):
        if idx == 0:  # 第1题
            result1.append([choice_mapping_data1[1][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[1])])
        elif idx == 1:  # 第5题
            result1.append([choice_mapping_data1[5][i - 1] for i in values if 1 <= i <= len(choice_mapping_data1[5])])

    # 处理 data3：第4题
    question_num = 4  # 第4题
    if question_num in choice_mapping_data3:
        group_results = choice_mapping_data3[question_num]  # 获取第4题的12个范围
        for i, group in enumerate(group_results):
            # 对于每个范围的值，只取第一个值来表示
            if len(data3) > i and data3[i]:  # 确保索引不超出范围
                result3.append(group[data3[i][0] - 1] if 1 <= data3[i][0] <= len(group) else group[0])

    # 随机从每个题目的选项范围中选取一个数，并组成一个结果列表
    result2 = [random.choice(options) for options in choice_mapping_data2.values()]

    return result1, result2, result3


if __name__ == '__main__':
    window()

